<?php
if (!isset($_GET['id'])) {
    die("Missing 'id' parameter");
}

$requestUrl = "https://zlisc.com/news/" . urlencode($_GET['id']) . ".html";
var_dump($requestUrl);

// 最大重定向次数
$maxRedirects = 5;
$currentUrl = $requestUrl;
$redirectCount = 0;

do {
    $urlParts = parse_url($currentUrl);
    $host = $urlParts['host'];
    $path = isset($urlParts['path']) ? $urlParts['path'] : '/';
    if (isset($urlParts['query'])) {
        $path .= '?' . $urlParts['query'];
    }

    $clientUA = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'Mozilla/5.0';
    $clientReferer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : $currentUrl;

    // 尝试通过fsockopen连接（忽略SSL验证）
    $fp = @fsockopen('ssl://' . $host, 443, $errno, $errstr, 30);
    if (!$fp) {
        // 尝试非SSL连接
        $fp = @fsockopen($host, 80, $errno, $errstr, 30);
        if (!$fp) {
            die("Connection failed: $errstr ($errno)");
        }
        $protocol = 'HTTP/1.1';
    } else {
        $protocol = 'HTTP/1.1';
    }

    // 构建HTTP请求
    $request = "GET $path $protocol\r\n";
    $request .= "Host: $host\r\n";
    $request .= "User-Agent: $clientUA\r\n";
    if (!empty($clientReferer)) {
        $request .= "Referer: $clientReferer\r\n";
    }
    $request .= "Connection: Close\r\n\r\n";

    fwrite($fp, $request);
    $response = '';

    while (!feof($fp)) {
        $response .= fgets($fp, 128);
    }
    fclose($fp);

    // 分离响应头和内容
    list($headers, $content) = explode("\r\n\r\n", $response, 2);

    // 解析HTTP状态码
    preg_match('/HTTP\/\d\.\d (\d+)/', $headers, $matches);
    $httpCode = isset($matches[1]) ? $matches[1] : 0;

    // 检查是否为重定向
    if (in_array($httpCode, array(301, 302, 303, 307, 308))) {
        // 提取Location头
        preg_match('/Location: ([^\r\n]+)/i', $headers, $locationMatches);
        if (isset($locationMatches[1])) {
            $newUrl = $locationMatches[1];

            // 处理相对URL
            if (strpos($newUrl, 'http') !== 0) {
                $baseUrl = ($urlParts['scheme'] ?? 'http') . '://' . $host;
                $newUrl = $baseUrl . $newUrl;
            }

            $currentUrl = $newUrl;
            $redirectCount++;
            echo "Redirecting to: $currentUrl ({$redirectCount}/{$maxRedirects})\n";

            // 防止无限重定向
            if ($redirectCount > $maxRedirects) {
                die("Too many redirects ({$redirectCount})");
            }
        } else {
            die("Redirect response without Location header");
        }
    } else {
        // 非重定向状态码，退出循环
        break;
    }
} while (true);

// 检查最终HTTP状态码
if ($httpCode != 200) {
    die("HTTP Error: {$httpCode}");
}

echo $content;
?>